<template>
	<xn-form-container
		:title="formData.id ? '编辑采购记录' : '增加采购记录'"
		:width="700"
		v-model:open="open"
		:destroy-on-close="true"
		@close="onClose"
	>
		<a-form ref="formRef" :model="formData" :rules="formRules" layout="vertical">
			<a-form-item label="类型：" name="type">
				<a-select v-model:value="formData.type" placeholder="请选择类型" :options="typeList" />
			</a-form-item>
			<a-form-item label="资产类别：" name="commodityName">
				<a-select v-model:value="formData.commodityCode" @change="changeCommodityName">
					<a-select-option v-for="option in commodity" :key="option.code" :value="option.code" :label="option.name">
						{{ option.name }}
					</a-select-option>
				</a-select>
			</a-form-item>
			<a-form-item v-show="visible" label="办公用品类型" name="officeSupplie">
				<a-select
					v-model:value="formData.officeSupplies"
					placeholder="请选择案件状态"
					:options="OfficeSupplies"
					allowClear
				/>
			</a-form-item>

			<!--			<a-form-item label="供应商名称：" name="supplierName">-->
			<!--				<a-input v-model:value="formData.supplierName" placeholder="请输入供应商" allow-clear />-->
			<!--			</a-form-item>-->
			<a-form-item label="供应商名称：" name="supplierId">
				<a-select v-model:value="formData.supplierId">
					<a-select-option
						v-for="option in commoditySupplierList"
						:key="option.id"
						:value="option.id"
						:label="option.supplierName"
						allow-clear
					>
						{{ option.supplierName }}
					</a-select-option>
				</a-select>
			</a-form-item>

			<a-form-item label="采购方式：" name="purchaseType">
				<a-select v-model:value="formData.purchaseType" placeholder="请选择类型" :options="purchaseTypeList" />
			</a-form-item>
			<a-form-item label="计费方式：" name="billingType">
				<a-select v-model:value="formData.billingType" placeholder="请选择类型" :options="billingTypeList" />
			</a-form-item>
			<a-form-item label="采购数量：" name="purchaseQuantity">
				<a-input
					v-model:value="formData.purchaseQuantity"
					placeholder="请输入采购数量"
					@input="handlePurchaseQuantityInput"
					@change="updateTotalPrice"
					allow-clear
				/>
			</a-form-item>
			<a-form-item label="单价：" name="unitPrice">
				<a-input
					v-model:value="formData.unitPrice"
					placeholder="请输入采购单价"
					@input="handlePurchaseQuantityInput"
					@change="updateTotalPrice"
					allow-clear
				/>
			</a-form-item>
			<a-form-item label="总价：" name="totalPrice">
				<a-input v-model:value="formData.totalPrice" placeholder="总价" allow-clear aria-readonly="true" />
			</a-form-item>
			<a-form-item label="采购/预算月份：" name="month">
				<a-date-picker
					v-model:value="formData.month"
					picker="month"
					value-format="YYYY-MM"
					placeholder="请选择采购/预算月份"
				/>
			</a-form-item>
			<a-form-item label="成本部门" name="neededDepartment">
				<DeptSelect v-model:value="formData.neededDepartment" />
			</a-form-item>
			<a-form-item label="" name="projectCode">
				<ProjectSelect v-model:value="formData.projectCode" />
			</a-form-item>
			<a-form-item label="使用地址：" name="address">
				<a-input v-model:value="formData.address" placeholder="请输入使用地址" allow-clear />
			</a-form-item>
		</a-form>
		<template #footer>
			<a-button style="margin-right: 8px" @click="onClose">关闭</a-button>
			<a-button type="primary" @click="onSubmit" :loading="submitLoading">保存</a-button>
		</template>
	</xn-form-container>
</template>

<script setup name="amsPurchaseOrderForm">
	import { cloneDeep } from 'lodash-es'
	import { required } from '@/utils/formRules'
	import amsPurchaseOrderApi from '@/api/ams/purchase/amsPurchaseOrderApi'
	import amsCommodityInfoApi from '@/api/ams/commodity/amsCommodityInfoApi'
	import bizUserApi from '@/api/biz/bizUserApi'
	import tool from '@/utils/tool'
	import commoditySupplierApi from '@/api/ams/supplier/commoditySupplierApi'
	import ProjectSelect from '@/components/Tjzy/Project/index.vue'
	import DeptSelect from '@/components/Tjzy/Dept/index.vue'
	// 抽屉状态
	const open = ref(false)
	const emit = defineEmits({ successful: null })
	const formRef = ref()
	const OfficeSupplies = tool.dictList('Office_supplies')
	const visible = ref(false)
	// 表单数据
	const formData = ref({
		type: 1,
		commodityName: '',
		purchaseType: 1,
		billingType: 1,
		purchaseQuantity: 1,
		unitPrice: 1,
		totalPrice: 1,
		month: '',
		neededDepartment: '',
		projectCode: '',
		address: '',
		officeSupplies: undefined,
		commodityCode: '',
		supplierId: ''
	})
	const submitLoading = ref(false)
	const typeList = ref([
		{
			value: 1,
			label: '实付'
		},
		{
			value: 2,
			label: '预算'
		}
	])
	const purchaseTypeList = ref([
		{
			value: 1,
			label: '购买'
		},
		{
			value: 2,
			label: '租赁'
		}
	])
	const billingTypeList = ref([
		{
			value: 1,
			label: '包月'
		},
		{
			value: 2,
			label: '计件'
		}
	])
	// 打开抽屉
	const onOpen = (record) => {
		open.value = true
		if (record) {
			console.log('--------')
			console.log(record)
			let recordData = cloneDeep(record)
			formData.value = Object.assign({}, recordData)
		}
	}
	const treeDefaultExpandedKeys = ref([])

	// 关闭抽屉
	const onClose = () => {
		formRef.value.resetFields()
		formData.value = {}
		open.value = false
	}
	// 默认要校验的
	const formRules = {
		type: [required('请选择类型')],
		commodityCode: [required('请选择资产类别')],
		supplierId: [required('请输入供应商名称')],
		purchaseType: [required('请选择采购方式')],
		billingType: [required('请选择计费方式')],
		purchaseQuantity: [required('请输入采购数量')],
		unitPrice: [required('请输入单价')],
		month: [required('请选择月份')],
		neededDepartment: [required('请输入成本部门')]
	}
	// 处理输入事件，确保仅能输入数字
	const handlePurchaseQuantityInput = (event) => {
		let value = event.target.value
		// 使用正则表达式移除非数字字符
		value = value.replace(/[^\d]/g, '')
		formData.purchaseQuantity = value
	}
	// 更新总价
	const updateTotalPrice = () => {
		if (formData.value.purchaseQuantity && !isNaN(formData.value.unitPrice)) {
			formData.value.totalPrice = parseFloat(formData.value.purchaseQuantity) * parseFloat(formData.value.unitPrice)
		} else {
			alert('请输入正确的采购数量和单价')
			formData.value.totalPrice = 0
		}
	}
	const commodity = ref([])
	const commoditySupplierList = ref([])
	// 验证并提交数据
	const onSubmit = () => {
		formRef.value
			.validate()
			.then(() => {
				submitLoading.value = true
				const formDataParam = cloneDeep(formData.value)
				console.log('----')
				console.log(formDataParam)
				console.log('----')
				amsPurchaseOrderApi
					.amsPurchaseOrderSubmitForm(formDataParam, formDataParam.id)
					.then(() => {
						onClose()
						emit('successful')
					})
					.finally(() => {
						submitLoading.value = false
					})
			})
			.catch(() => {})
	}

	const changeCommodityName = (val) => {
		if (val === 'WORK_USE') {
			visible.value = true
		} else {
			visible.value = false
			formData.value.officeSupplies = undefined
		}
	}
	// 抛出函数
	defineExpose({
		onOpen
	})
	onMounted(() => {
		// 获取项目列表
		amsCommodityInfoApi.amsCommodityList().then((res) => {
			commodity.value = res
		})
		commoditySupplierApi.commoditySupplierAll().then((res) => {
			commoditySupplierList.value = res
		})
	})
</script>
